<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="active">
          <el-tab-pane label="角色管理" name="role">
            <el-button icon="el-icon-plus" type="primary" @click="addrole">新增角色</el-button>
            <el-table
              v-loading="showloading"
              :data="tableData"
              border
              style="width: 100%"
            >

              <el-table-column
                label="序号"
                type="index"
                :index="indexMethod"
                width="150"
              />
              <el-table-column
                prop="name"
                label="角色名"
                width="150"
              />
              <el-table-column
                prop="description"
                label="描述"
              />

              <el-table-column label="操作" width="300" align="center">
                <template v-slot="{row}">
                  <el-button type="text" @click="showAssign(row.id)">分配权限</el-button>
                  <el-button type="text" @click="editrole(row.id)">修改</el-button>
                  <el-button type="text" @click="delrole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-pagination

              background

              :page-sizes="[5, 10, 15]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next"
              :total="total"
              @current-change="currentChange"
              @size-change="sizeChange"
            />
          </el-tab-pane>

          <el-tab-pane label="公司信息" name="company">
            <el-form label-width="100px" style="margin-left: 100px">
              <el-form-item label="企业名称">
                <el-input :value="company.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input :value="company.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="企业电话">
                <el-input :value="company.companyPhone" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input :value="company.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" :value="company.remarks" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>

        </el-tabs>
      </el-card>

      <el-dialog :visible.sync="showadd" :title="from.id? '编辑角色' : '添加角色'" @close="close">
        <el-form ref="froms" :model="from" label-width="100px" :rules="rules">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="from.name" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="from.description" placeholder="请输入描述" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="yesadd">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 分配权限的弹层 -->
      <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog">

        <el-tree
          ref="tree"
          v-loading="loading"
          node-key="id"
          :data="permissionData"
          :props="defaultProps"
          :default-expand-all="true"
          :show-checkbox="true"
          :check-strictly="true"
        />
        <template #footer>
          <div style="text-align: right;">

            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="assignPermission">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getallroleres, addroleRes, delroleRes, getidroleRes, changeroleRes, getCompanyById, assignPerm } from '@/api/setting'
import { getPermissionList } from '@/api/permission'
import { listToTree } from '@/utils/index'
export default {
  name: 'Settings',
  data() {
    // 验证输入的名称是否重复
    const validaname = async(rule, value, callback) => {
      if (this.from.id) {
        if (this.oldname === value) {
          callback()
        } else {
          const { rows } = await getallroleres('1', this.total)
          rows.some(item => item.name === value) ? callback(new Error('名称重复')) : callback()
        }
      }
      const { rows } = await getallroleres('1', this.total)
      rows.some(item => item.name === value) ? callback(new Error('名称重复')) : callback()
    }

    return {
      from: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true }, { validator: validaname, trigger: 'blur' }]

      },
      roleId: '',
      tableData: [],
      total: 1,
      pagesize: 5,
      page: 1,
      loading: false,
      showloading: false,
      showadd: false,
      oldname: '',
      active: 'role',
      company: {},
      showAssignDialog: false,
      permissionData: [],
      defaultProps: {
        label: 'name'
      }
    }
  },
  watch: {
    async active(value) {
      if (value === 'company') {
        const id = this.$store.state.user.UserInfo.companyId
        // 发送请求-获取公司的信息
        const res = await getCompanyById(id)
        this.company = res
      }
    }
  },

  async created() {
    this.getallrole()
  },

  methods: {
    async getallrole() {
      this.showloading = true
      const res = await getallroleres(this.page, this.pagesize)
      this.total = res.total
      this.tableData = res.rows
      this.showloading = false
    },

    // 改变当前页的请求
    currentChange(value) {
      this.page = value
      this.getallrole()
    },
    // 改变每页显示的条数
    sizeChange(value) {
      this.pagesize = value
      this.getallrole()
    },

    // 新增角色显示
    addrole() {
      this.showadd = true
    },

    // 确认添加角色信息或确认编辑信息
    yesadd() {
      this.$refs.froms.validate(async(valid) => {
        if (valid) {
          if (this.from.id) {
            await changeroleRes(this.from)
            this.showadd = false
            this.$message.success('操作成功')
            this.getallrole()
            return
          }
          await addroleRes(this.from)
          this.showadd = false
          this.$message.success('操作成功')
          this.getallrole()
        } else {
          return
        }
      })
    },
    // 关闭showadd弹框
    close() {
      this.from = {
        name: '',
        description: ''
      }
      this.showadd = false
      this.$refs.froms.resetFields()
    },
    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.pagesize
    },
    // 删除角色
    async delrole(id) {
      try {
        await this.$confirm('你确定要删除该角色吗', '温馨提示', {
          type: 'warning'
        })
      } catch {
        return
      }
      await delroleRes(id)
      this.$message.success('删除成功')
      console.log(this.tableData.length)
      console.log(this.page - 1)
      if (this.tableData.length === 1 && this.page !== 1) {
        this.page--
        this.$nextTick()
        this.getallrole()
      } else { this.getallrole() }
    },

    // 编辑角色
    async editrole(id) {
      this.showadd = true
      const res = await getidroleRes(id)
      this.from = res
      this.oldname = res.name
    },

    // 分配权限
    async showAssign(id) {
      this.loading = true
      this.roleId = id
      this.showAssignDialog = true
      const res = await getPermissionList()
      this.permissionData = listToTree(res, '0')
      const { permIds } = await getidroleRes(id)
      this.$refs.tree.setCheckedKeys(permIds)
      this.loading = false
    },
    // 更改后确认更改角色权限
    async assignPermission() {
      const permIds = this.$refs.tree.getCheckedKeys()
      await assignPerm({
        id: this.roleId,
        permIds
      })
      this.closeAssignDialog()
      this.$message.success('操作成功')
    },
    // 关闭分配权限显示框
    closeAssignDialog() {
      this.showAssignDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-pagination {
    float: right;
  }
</style>>
